package com.renwei.yunlong.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.work.GuideWebActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.GetTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.wheelview.OnWheelChangedListener;
import com.renwei.yunlong.wheelview.WheelView;
import com.renwei.yunlong.wheelview.adapter.ArrayWheelAdapter;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * 滚动选择日期、时间
 * <p>
 * 去现场、非现场、接受 -- 页面
 * <p>
 * Created by Administrator on 2017/9/11.
 */

public class WorkDatePopWindow extends PopupWindow implements View.OnClickListener, HttpTaskListener, OnWheelChangedListener {
    protected ServiceLoginBean serviceLoginBean;
    protected LoginBean ownerBean;
    private Context mContext;
    private String ymdData[] = new String[720];
    private String pager;
    private TextView tv_cancle;
    private TextView tv_title;
    private TextView tv_ok;
    private TextView tv_complete;
    private WheelView wl_ymd;
    private WheelView wl_week;
    private WheelView wl_hour;
    private WheelView wl_min;
    String[] week_str =
            {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    String[] xiaoshi_start =
            {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
                    "19", "20", "21", "22", "23"};

    String[] fenzhong_start =
            {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
                    "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36",
                    "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54",
                    "55", "56", "57", "58", "59"};
    private long currentTime;
    private String requestId;
    private String eventId;
    private int currentId;
    private String companyType;
    private String YMD = "";
    private String HOUR = "";
    private String MIN = "";
    private int code = 0;
    private ArrayWheelAdapter<String> weekAdapter;
    private ArrayWheelAdapter<String> hourAdapter;
    private ArrayWheelAdapter<String> minAdapter;
    onDataSelectListener listener;

    public void setListener(onDataSelectListener listener) {
        this.listener = listener;
    }

    public interface onDataSelectListener {
        void onErrorMsg(String msg);

        void onMsg(String msg);

        void onSuccessMsg(String msg);

        void onSelectDate(Intent data, int code);
    }

    private WorkDatePopWindow(Context context, int width, int height) {
        this.mContext = context;
        // 设置可以获得焦点
        setFocusable(true);
        // 设置弹窗内可点击
        setTouchable(true);
        setAnimationStyle(R.style.pop_bottom_show);
        // 设置弹窗外可点击
        setOutsideTouchable(false);
        // 设置弹窗的宽度和高度
        setWidth(width);
        setHeight(height);
    }

    /**
     * @param context     context
     * @param companyType companyType
     * @param requestId   requestId
     * @param eventId     eventId
     * @param pager       pager
     */
    public WorkDatePopWindow(Context context, String companyType, String requestId, String eventId, String pager, ServiceLoginBean serviceLoginBean, LoginBean ownerBean, int code) {
        this(context, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.pop_date_selecter, null);
        setContentView(view);
        tv_cancle = view.findViewById(R.id.tv_cancle);
        tv_title = view.findViewById(R.id.tv_title);
        tv_ok = view.findViewById(R.id.tv_ok);
        tv_complete = view.findViewById(R.id.tv_complete);
        wl_ymd = view.findViewById(R.id.wl_ymd);
        wl_week = view.findViewById(R.id.wl_week);
        wl_hour = view.findViewById(R.id.wl_hour);
        wl_min = view.findViewById(R.id.wl_min);
        this.serviceLoginBean = serviceLoginBean;
        this.ownerBean = ownerBean;
        this.mContext = context;
        this.requestId = requestId;
        this.eventId = eventId;
        this.pager = pager;
        this.companyType = companyType;
        this.code = code;
        initData();
        initView();
    }


    //初始化数据
    private void initData() {
        currentTime = System.currentTimeMillis();
        long day = 24 * 60 * 60 * 1000;
        if ("开始时间".equals(pager) || "结束时间".equals(pager)) {
            long lastYear = currentTime - day * 360;
            for (int i = 0; i < 720; i++) {
                long time = lastYear + day * i;
                if (time == currentTime) {
                    currentId = i;
                }
                ymdData[i] = GetTimeUtils.getYMDTime(time);
            }
        } else {
            for (int i = 0; i < 720; i++) {
                long time = currentTime + day * i;
                ymdData[i] = GetTimeUtils.getYMDTime(time);
            }
        }
        YMD = GetTimeUtils.getYMDTime(currentTime);
    }

    private void initView() {
        if ("接受".equals(pager)) {
            tv_title.setText("接受");
            TextView titleView = tv_title;
            Drawable titleLeft = mContext.getResources().getDrawable(R.mipmap.icon_title_help);
            titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
            titleView.setCompoundDrawables(null, null, titleLeft, null);
            titleView.setCompoundDrawablePadding(10);
            titleView.setOnClickListener(this);
            tv_complete.setText("预计开始处理时间");
        } else if ("去现场".equals(pager)) {
            tv_title.setText("去现场");
            tv_complete.setText("预计到场时间");
        } else if ("非现场".equals(pager)) {
            tv_title.setText("非现场");
            tv_complete.setText("预计开始处理时间");
        } else if ("到场时间".equals(pager)) {
            tv_title.setText("到场时间");
            tv_complete.setText("预计到场时间");
        } else if ("开始时间".equals(pager)) {
            tv_title.setText("开始时间");
            tv_complete.setText("开始时间");
        } else if ("结束时间".equals(pager)) {
            tv_title.setText("结束时间");
            tv_complete.setText("结束时间");
        }
        tv_cancle.setOnClickListener(this);
        tv_ok.setOnClickListener(this);
        initWheelView();
    }

    private void initWheelView() {
        ArrayWheelAdapter<String> ymdAdapter = new ArrayWheelAdapter<>(mContext);
        ymdAdapter.setData(ymdData);
        ymdAdapter.setTextSize(18);
        wl_ymd.setViewAdapter(ymdAdapter);
        wl_ymd.setCurrentItem(currentId);
        wl_ymd.addChangingListener(this);

        weekAdapter = new ArrayWheelAdapter<>(mContext);
        weekAdapter.setTextSize(18);
        wl_week.setViewAdapter(weekAdapter);
        wl_week.setEnabled(false);

        hourAdapter = new ArrayWheelAdapter<>(mContext);
        hourAdapter.setTextSize(18);
        wl_hour.setViewAdapter(hourAdapter);
        wl_hour.addChangingListener(this);

        minAdapter = new ArrayWheelAdapter<>(mContext);
        minAdapter.setTextSize(18);
        wl_min.setViewAdapter(minAdapter);
        wl_min.addChangingListener(this);

        if ("开始时间".equals(pager) || "结束时间".equals(pager)) {
            wl_ymd.setCyclic(true);
            wl_week.setCyclic(true);
            wl_hour.setCyclic(true);// 可循环滚动
            wl_min.setCyclic(true);// 可循环滚动
        } else {
            wl_ymd.setCyclic(false);
            wl_week.setCyclic(false);
            wl_hour.setCyclic(false);// 可循环滚动
            wl_min.setCyclic(false);// 可循环滚动
        }

        Calendar c = Calendar.getInstance();
        int curYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);
        changeWeek(curYear, curMonth, curDate, 0);
        changeHour(0);
        changeMin(0);
    }

    private void confirm() {
        HttpPresenter hp = new HttpPresenter(mContext);
        hp.setshowDialogcontent("正在加载");
        hp.setUrl(getUrl());
        hp.putParam("jsonBean", getJson());
        hp.setCallBack(this);
        hp.post();
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
        params.alpha = 0.5f;
        ((Activity) mContext).getWindow().setAttributes(params);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
        params.alpha = 1f;
        ((Activity) mContext).getWindow().setAttributes(params);
    }

    private String getUrl() {
        String url = "";
        if ("接受".equals(pager)) {
            if ("1".equals(companyType)) {
                url = Api.$().OWNER_JIEDAN_URL;
            } else if ("2".equals(companyType)) {
                url = Api.$().SERVICE_JIEDAN_URL;
            }
        } else if ("去现场".equals(pager) || "非现场".equals(pager)) {
            if ("1".equals(companyType)) {
                url = Api.$().OWNER_XIANCHANG_URL;
            } else if ("2".equals(companyType)) {
                url = Api.$().SERVICE_XIANCHANG_URL;
            }
        } else if ("到场时间".equals(pager)) {
            if ("1".equals(companyType)) {

            } else if ("2".equals(companyType)) {

            }
        }
        return url;
    }

    private String getJson() {
        String processTimes = YMD + " " + HOUR + ":" + MIN;
        HashMap<String, String> map = new HashMap<>();
        if ("接受".equals(pager)) {
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("processTimes", processTimes);
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
        } else if ("去现场".equals(pager) || "非现场".equals(pager)) {
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("processTimes", processTimes);
            if ("去现场".equals(pager)) {
                map.put("treatment", "1");
            } else if ("非现场".equals(pager)) {
                map.put("treatment", "2");
            }
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
        } else if ("到场时间".equals(pager)) {
            if ("1".equals(companyType)) {

            } else if ("2".equals(companyType)) {

            }
        }
        return JsonMapUtil.mapToJson(map);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancle:
                dismiss();
                break;
            case R.id.tv_ok:
                if ("开始时间".equals(pager) || "结束时间".equals(pager) || "到场时间".equals(pager)) {
                    dismiss();
                    String processTimes = YMD + " " + HOUR + ":" + MIN;
                    Intent intent = new Intent();
                    intent.putExtra("time", processTimes);
                    listener.onSelectDate(intent, code);
                } else {
                    confirm();
                }
                break;
            case R.id.option_textview_title:
                GuideWebActivity.openActivity(mContext, Api.$().GUIDE_ACCEPT_WORK_URI);
                break;
            default:
                break;
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        switch (wheel.getId()) {
            case R.id.wl_ymd:
                YMD = ymdData[newValue];
                int year = Integer.parseInt(YMD.substring(0, YMD.indexOf("-")));
                int month = Integer.parseInt(YMD.substring(YMD.indexOf("-") + 1, YMD.lastIndexOf("-")));
                int day = Integer.parseInt(YMD.substring(YMD.lastIndexOf("-") + 1, YMD.length()));

                changeWeek(year, month, day, newValue);
                changeHour(newValue);
                changeMin(newValue);
                break;
            case R.id.wl_hour:
                HOUR = hourAdapter.getData()[newValue];
                break;
            case R.id.wl_min:
                MIN = minAdapter.getData()[newValue];
                break;
            default:
                break;
        }
    }

    private void changeWeek(int year, int month, int day, int newValue) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            weekAdapter.setData(CommonUtils.getListIntArray(week_str, i).get(1));
            wl_week.setCurrentItem(0);
        } else {
            weekAdapter.setData(week_str);
            wl_week.setCurrentItem(i);
        }
    }

    private void changeHour(int newValue) {
        HOUR = new SimpleDateFormat("HH").format(Calendar.getInstance().getTime());
        List<String> list = Arrays.asList(xiaoshi_start);
        int i = list.indexOf(HOUR);
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            hourAdapter.setData(CommonUtils.getListIntArray(xiaoshi_start, i).get(1));
            wl_hour.setCurrentItem(0);
        } else {
            hourAdapter.setData(xiaoshi_start);
            wl_hour.setCurrentItem(i);
        }
    }

    private void changeMin(int newValue) {
        MIN = new SimpleDateFormat("mm").format(Calendar.getInstance().getTime());
        List<String> list = Arrays.asList(fenzhong_start);
        int i = list.indexOf(MIN);
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            minAdapter.setData(CommonUtils.getListIntArray(fenzhong_start, i).get(1));
            wl_min.setCurrentItem(0);
        } else {
            minAdapter.setData(fenzhong_start);
            wl_min.setCurrentItem(i);
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        EventBus.getDefault().post(new WorkPageRefreshEvent());
        CommonBean bean = new Gson().fromJson(result, CommonBean.class);
        if (bean.getMessage().getCode() == 200) {
            dismiss();
            listener.onSuccessMsg(StringUtils.value(bean.getMessage().getMessage()));
        } else {
            listener.onMsg(bean.getMessage().getMessage());
        }
    }

    @Override
    public void onException(int requestId, String code) {
        listener.onErrorMsg(mContext.getResources().getString(R.string.net_work_error));
    }


}
